package service

import (
	"context"
	"encoding/json"
	"time"

	log "github.com/sirupsen/logrus"
	"task/driver"
	"task/models"
)

// StartBusiness1 start business1.
func StartBusiness1(ctx context.Context, msg []byte) error {
	var err error
	// 解析消息
	event := new(models.BusinessEvent)
	if err = json.Unmarshal(msg, &event); err != nil {
		log.Errorf("Unmarshal message error(%v)", err)
		return err
	}
	switch event.Event {
	case models.BusinessEventName:
		// 模拟业务处理15ms
		time.Sleep(15 * time.Millisecond)
		SendCallback(ctx, event)
	default:
		log.Errorf("business1 event(%s) not found", event.Event)
	}
	return nil
}

// StartBusiness2 start business2.
func StartBusiness2(ctx context.Context, msg []byte) error {
	var err error
	// 解析消息
	event := new(models.BusinessEvent)
	if err = json.Unmarshal(msg, &event); err != nil {
		log.Errorf("Unmarshal message error(%v)", err)
		return err
	}
	switch event.Event {
	case models.BusinessEventName:
		// 模拟业务处理15ms
		time.Sleep(15 * time.Millisecond)
		SendCallback(ctx, event)
	default:
		log.Errorf("business2 event(%s) not found", event.Event)
	}
	return nil
}

// SendCallback send callback.
func SendCallback(ctx context.Context, event *models.BusinessEvent) {
	var err error
	if err = driver.SendCallbackEventMsg(ctx, &models.CallbackEvent{
		ResourceId:  event.ResourceId,
		ProcessorId: event.ProcessorId,
		Result:      15,
	}); err != nil {
		return
	}
	return
}
